package com.hua.yuan.ui;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.hua.yuan.R;
import com.hua.yuan.base.Constents;
import com.hua.yuan.common.BaseActivity;
import com.hua.yuan.ui.adapter.ImageCommonAdapter;
import com.hua.yuan.ui.data.PictureDataRequest;
import com.hua.yuan.ui.module.ImageDetail;
import com.hua.yuan.ui.module.ImageDetailCommonBean;
import com.hua.yuan.ui.module.ImageDetailTuijianBean;
import com.hua.yuan.util.JsonUtil;
import com.hua.yuan.util.ToastUtil;
import com.hua.yuan.util.loadimage.DownImageUtil;
import com.hua.yuan.util.loadimage.ImageCallBack;
import com.hua.yuan.util.loadimage.XPermissionUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cm.hua.yuan.common.utils.PreferenceUtils;
import okhttp3.Call;

/**
 * Created by huangyang on 2018/7/22.
 * 图集的详情页
 */

public class ImageDetailActivity extends BaseActivity implements View.OnClickListener {

    private ImageView backImage;
    private TextView titleView;
    private ScrollView sv_layout;
    private ImageView iv_cover;
    private RelativeLayout rl_intro_detail;
    private TextView iv_atlas_desc;
    private TextView iv_intro;
    private TextView tv_sees;
    private TextView tv_lable;
    private TextView tv_images;
    private TextView tv_daibi;
    private LinearLayout llId1;
    private LinearLayout ll_relate;
    private ListView lv_comment;

    private EditText sendEt;
    private TextView videoDisSendTv;
    private LinearLayout buttonBuyLl;
    private LinearLayout buttonCollectLl;
    private LinearLayout buttonDownLl;
    private ImageView collImage;

    private RelativeLayout buyRlView;
    private TextView videoNameShow;
    private TextView videoBuyMoney;
    private TextView videoKaiTongVip;
    private TextView videoCancelTv;

    private int id;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_detail);

        id = getIntent().getIntExtra("id", 0);

        initView();
        initData();
    }

    private void initView() {
        backImage = findViewById(R.id.backImage);
        titleView = findViewById(R.id.titleView);
        backImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        sv_layout = findViewById(R.id.sv_layout);
        iv_cover = findViewById(R.id.iv_cover);
        iv_atlas_desc = findViewById(R.id.iv_atlas_desc);
        iv_intro = findViewById(R.id.iv_intro);
        tv_sees = findViewById(R.id.tv_sees);
        tv_lable = findViewById(R.id.tv_lable);
        tv_images = findViewById(R.id.tv_images);
        tv_daibi = findViewById(R.id.tv_daibi);
        llId1 = findViewById(R.id.llId1);
        ll_relate = findViewById(R.id.ll_relate);
        lv_comment = findViewById(R.id.lv_comment);
        collImage = findViewById(R.id.collImage);
        rl_intro_detail = findViewById(R.id.rl_intro_detail);

        sendEt = findViewById(R.id.sendEt);
        videoDisSendTv = findViewById(R.id.videoDisSendTv);
        buttonBuyLl = findViewById(R.id.buttonBuyLl);
        buttonCollectLl = findViewById(R.id.buttonCollectLl);
        buttonDownLl = findViewById(R.id.buttonDownLl);

        buyRlView = findViewById(R.id.buyRlView);
        videoNameShow = findViewById(R.id.videoNameShow);
        videoBuyMoney = findViewById(R.id.videoBuyMoney);
        videoKaiTongVip = findViewById(R.id.videoKaiTongVip);
        videoCancelTv = findViewById(R.id.videoCancelTv);

        buttonBuyLl.setOnClickListener(this);
        buttonCollectLl.setOnClickListener(this);
        buttonDownLl.setOnClickListener(this);
        videoDisSendTv.setOnClickListener(this);
        rl_intro_detail.setOnClickListener(this);
        videoBuyMoney.setOnClickListener(this);
        videoKaiTongVip.setOnClickListener(this);
        videoCancelTv.setOnClickListener(this);
    }

    private void setData(final ImageDetail imageDetail) {
        //封面
        Glide.with(ImageDetailActivity.this)
                .load(imageDetail.getImg_url())
                .into(iv_cover);

        titleView.setText(imageDetail.getTitle());
        iv_atlas_desc.setText(imageDetail.getTitle());
        tv_sees.setText(imageDetail.getPlay_num());
        tv_lable.setText(imageDetail.getClassifyDesc());
        tv_images.setText(imageDetail.getPictures_list().size() + "张");

        tv_daibi.setText(imageDetail.getNow_price() + "代币");

        //显示是收藏
        if ("0".equals(imageDetail.getHas_collect())) {
            //没有藏收藏
            collImage.setImageResource(R.mipmap.video_dis_bottom_2);

        } else {
            //收藏了
            collImage.setImageResource(R.mipmap.video_dis_comment_c1);

        }


        videoNameShow.setText("您还未购买本图集");
        videoBuyMoney.setText(imageDetail.getNow_price() + "代币购买本图集");
        videoKaiTongVip.setText("开通会员免费看");
        videoCancelTv.setText("取消");

        receiver = new MyBroadcastReceiver();
        myRegister();

        mDownImageUtil = new DownImageUtil(ImageDetailActivity.this);
        //图片回调处理
        mDownImageUtil.setImageCallBack(new ImageCallBack() {
            @Override
            public void onSuccess(String url) {
                Toast.makeText(ImageDetailActivity.this, "图片保存成功：" + url, Toast.LENGTH_SHORT).show();
                loadCount++;
                if (loadCount < imageDetail.getPictures_list().size()) {
                    mDownImageUtil.onDownLoad(
                            imageDetail.getPictures_list().get(loadCount).getImg_url(),
                            (int) System.currentTimeMillis(),
                            "tuji");
                }
            }

            @Override
            public void onFailed() {

            }
        });
    }

    private void myRegister() {
        if (receiver != null) {
            IntentFilter filter = new IntentFilter();
            filter.addAction("go_to_buy");
            filter.addAction("delete_con_success");
            registerReceiver(receiver, filter);
        }
    }

    private void myUnRegister() {
        if (receiver != null) {
            unregisterReceiver(receiver);
            receiver = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        myUnRegister();
    }

    private MyBroadcastReceiver receiver;
    private String picture_id = "";
    int loadCount = 0;
    DownImageUtil mDownImageUtil;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.videoBuyMoney://xx代币购买本图集
                //买
                goActivity();
                buyRlView.setVisibility(View.GONE);
                break;
            case R.id.videoKaiTongVip://开通会员免费看
                //开通
                buyRlView.setVisibility(View.GONE);
                break;
            case R.id.videoCancelTv://取消
                buyRlView.setVisibility(View.GONE);
                break;
            case R.id.buttonBuyLl://购买

                if (imageDetail != null) {
                    if ("0".equals(imageDetail.getIs_free())) {
                        if ("0".equals(imageDetail.getHas_buy())) {
                            buyRlView.setVisibility(View.VISIBLE);
                        } else {
                            ToastUtil.showShortToast("您已经购买了该图集");
                        }
                    } else {
                        ToastUtil.showShortToast("本图集免费");
                    }
                }

                break;
            case R.id.buttonCollectLl://收藏
                //收藏
                if (isLogin()) {
                    collFun();
                }
                break;
            case R.id.buttonDownLl://下载

                //权限管理
                XPermissionUtils.requestPermissions(ImageDetailActivity.this, 1, new String[]{Manifest.permission
                        .READ_EXTERNAL_STORAGE, Manifest.permission
                        .WRITE_EXTERNAL_STORAGE}, new XPermissionUtils.OnPermissionListener() {
                    @Override
                    public void onPermissionGranted() {
                        //第一个参数为下载地址，第二个参数为图片名，第三个参数为目录名
                        //  地址为格式：/storage/emulated/0/cwj/img/Test/1.png
                        mDownImageUtil.onDownLoad(
                                imageDetail.getPictures_list().get(loadCount).getImg_url(),
                                (int) System.currentTimeMillis(),
                                "tuji");
                    }

                    @Override
                    public void onPermissionDenied() {
                        Toast.makeText(ImageDetailActivity.this, "请打开权限！", Toast.LENGTH_SHORT).show();
                    }
                });

                break;
            case R.id.videoDisSendTv://发送（评论）
                if (null != imageDetail) {
                    picture_id = imageDetail.getAtlas_id() + "";
                }
                String comment = sendEt.getText().toString();
                if (TextUtils.isEmpty(comment)) {
                    ToastUtil.showLongToast("请输入评论内容");
                    return;
                }

                PictureDataRequest.addPictureComment(picture_id, comment, new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        sendEt.setText("");
                        getCommentData();
                        ToastUtil.showLongToast("评论成功");
                    }
                });
                break;
            case R.id.rl_intro_detail://简介
                Intent intent = new Intent(this, ImageDetailBrowActivity.class);
                intent.putExtra("imageDetail", imageDetail);
                startActivity(intent);
                break;
        }
    }

    private ImageDetail imageDetail;

    private void initData() {
        PictureDataRequest.getPictureDetail("" + id, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    JSONObject jsonObject = new JSONObject(response);

                    if (!jsonObject.isNull("errno")) {
                        String code = jsonObject.getString("errno");

                        if ("0".equals(code)) {

                            if (!jsonObject.isNull("data")) {
                                JSONObject dataJson = jsonObject.getJSONObject("data");
                                imageDetail = JsonUtil.json2Bean(dataJson.toString(), ImageDetail.class);

                                setData(imageDetail);

                                getCommentData();

                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

        String token = PreferenceUtils.getString(Constents.TOKEN, "");
        //相关组图
        PictureDataRequest.getPictures(token, 1, 0, 3, 1, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    JSONObject jsonObject = new JSONObject(response);

                    if (!jsonObject.isNull("errno")) {
                        String code = jsonObject.getString("errno");

                        if ("0".equals(code)) {

                            if (!jsonObject.isNull("data")) {

                                JSONArray dataJson = jsonObject.getJSONArray("data");

                                Gson gson = new Gson();

                                List<ImageDetailTuijianBean> list = new ArrayList<>();

                                //ll_relate.removeAllViews();
                                for (int i = 0; i < dataJson.length(); i++) {
                                    JSONObject data = dataJson.getJSONObject(i);
                                    ImageDetailTuijianBean bean = gson.fromJson(data.toString(), ImageDetailTuijianBean.class);
                                    list.add(bean);

                                    ll_relate.addView(setItemLayout(bean));
                                }

                            }

                        }

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }
        });

    }

    private class MyBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if ("delete_con_success".equals(action)) {
                if (imageDetail != null) {
                    imageDetail.setHas_buy("1");
                }
            }
        }
    }


    private boolean colFlag = true;

    /**
     * 收藏或者取消收藏的功能
     */
    private void collFun() {

        if (!colFlag) {
            return;
        }

        colFlag = false;

        String cloType = "";

        if (imageDetail != null) {
            String ty = imageDetail.getHas_collect();
            if ("0".equals(ty)) {
                //没有收藏
                cloType = "1";
            } else {
                cloType = "0";
            }

        }

        final String type = cloType;
        PictureDataRequest.altasCollect(imageDetail.getAtlas_id() + "", type, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                colFlag = true;
                if (isFinishing()) {
                    return;
                }
                if ("0".equals(type)) {
                    ToastUtil.showShortToast("收藏失败");
                } else {
                    ToastUtil.showShortToast("取消收藏失败");
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (isFinishing()) {
                    return;
                }
                colFlag = true;
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (!jsonObject.isNull("errno")) {
                        String code = jsonObject.getString("errno");
                        if ("0".equals(code)) {


                            if ("1".equals(type)) {
                                ToastUtil.showShortToast("收藏成功");

                                if (buttonCollectLl != null) {
                                    collImage.setImageResource(R.mipmap.video_dis_comment_c1);
                                }

                                if (imageDetail != null) {

                                    imageDetail.setHas_collect("1");

                                }

                            } else {
                                ToastUtil.showShortToast("取消收藏成功");
                                if (collImage != null) {
                                    collImage.setImageResource(R.mipmap.video_dis_bottom_2);
                                }

                                if (imageDetail != null && imageDetail != null) {

                                    imageDetail.setHas_collect("0");

                                }

                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }
        });


    }

    private void goActivity() {

        boolean flag = PreferenceUtils.getBoolean(Constents.IS_LOGIN);
        if (flag) {
            //登录了直接跳转

            if (imageDetail != null) {
                String money = imageDetail.getNow_price();
                String id = imageDetail.getAtlas_id() + "";

                Intent intent = new Intent(ImageDetailActivity.this, MoneyBagActivity.class);
                intent.putExtra("buyMoney", money);
                intent.putExtra("movieId", id);
                intent.putExtra("isTuji", true);
                startActivity(intent);
//                finish();
            }


        } else {
            //没有登录 先登录
            startActivity(new Intent(this, LoginActivity.class));
        }
    }

    public boolean isLogin() {
        boolean flag = PreferenceUtils.getBoolean(Constents.IS_LOGIN);
        if (!flag) {
            //没有登录 先登录
            startActivity(new Intent(this, LoginActivity.class));
        }
        return flag;
    }


    private void getCommentData() {
        //获取评列表
        if (null != imageDetail) {
            picture_id = imageDetail.getAtlas_id() + "";
        }
        //获取评列表
        PictureDataRequest.getPictureComment(picture_id, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    JSONObject jsonObject = new JSONObject(response);

                    if (!jsonObject.isNull("errno")) {
                        String code = jsonObject.getString("errno");

                        if ("0".equals(code)) {

                            if (!jsonObject.isNull("data")) {
                                JSONArray dataJson = jsonObject.getJSONArray("data");
                                List<ImageDetailCommonBean> commonList = JsonUtil.json2List(dataJson.toString(), ImageDetailCommonBean.class);
                                ImageCommonAdapter adapter = new ImageCommonAdapter(ImageDetailActivity.this);
                                adapter.setList(commonList);

//                                ImageDesAdapter adapter = new ImageDesAdapter(ImageDetailActivity.this);
//                                adapter.setList(commonList);
                                lv_comment.setAdapter(adapter);
                                setListViewHeightBasedOnChildren(lv_comment);
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private View setItemLayout(final ImageDetailTuijianBean bean) {
        View itemLayout = View.inflate(ImageDetailActivity.this, R.layout.item_xiangguan, null);

        itemLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(ImageDetailActivity.this, ImageDetailActivity.class).putExtra("id", bean.getAtlas_id()));
            }
        });

        ImageView itemImage = itemLayout.findViewById(R.id.itemImage);

        TextView itemName = itemLayout.findViewById(R.id.itemName);//title
        TextView itemPlayCount = itemLayout.findViewById(R.id.itemPlayCount);//观看
        TextView tv_label = itemLayout.findViewById(R.id.tv_label);
        TextView itemJf = itemLayout.findViewById(R.id.itemJf);//代币
        TextView tv_pic_count = itemLayout.findViewById(R.id.tv_pic_count);

        //显示图片的地址
        Glide.with(ImageDetailActivity.this)
                .load(bean.getImg_url())
                .into(itemImage);

        //显示名字
        itemName.setText(bean.getTitle());

        //显示类型
        tv_label.setText(bean.getClassifyDesc());

        //代币
        itemJf.setText(bean.getNow_price() + "代币");

        //图片数量
        tv_pic_count.setText(bean.getPic_num() + "张");

        //显示播放次数
        int count;
        try {
            count = Integer.parseInt(bean.getPlay_num());
        } catch (NumberFormatException e) {
            count = 0;
        }
        if (count > 999) {
            itemPlayCount.setText("999+");
        } else {
            itemPlayCount.setText(String.valueOf(count));
        }

        return itemLayout;
    }


    /**
     * 动态设置ListView的高度 ,该方法必须在listview设置了adapter之后调用
     *
     * @param listView
     */
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        if (listView == null)
            return;

        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(50, 50);//置空，注意：这里的listview的子项的最大布局必须是LinearLayout布局
            totalHeight += listItem.getMeasuredHeight(); //循环得到listview的所有item高度的总和
        }

        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }
}
